/**
 * 聊天控制器
 * Chat Controller
 *
 * 功能说明:
 * - 处理来自不同聊天提供者的消息
 * - 管理用户认证流程
 * - 协调代理服务和上下文服务
 * - 处理特殊命令（如清除上下文）
 *
 * Features:
 * - Handle messages from different chat providers
 * - Manage user authentication flow
 * - Coordinate agent service and context service
 * - Handle special commands (like clearing context)
 */

import { AgentService } from '../service/agent.js';
import { ContextService } from '../service/context.js';
import { ChatProvider } from '../provider/type.js';
import { Express } from 'express';

/**
 * 聊天控制器类
 * Chat Controller Class
 * 负责协调多个聊天提供者的消息处理逻辑
 * Responsible for coordinating message processing logic across multiple chat providers
 */
export class ChatController {
  /**
   * 构造函数
   * Constructor
   * @param providers 聊天 Provider 数组 / Array of chat providers
   */
  constructor(private readonly providers: ChatProvider[]) {}

  /**
   * 注册所有聊天提供者的事件监听器和路由
   * Register event listeners and routes for all chat providers
   * @param app Express应用实例 / Express application instance
   */
  register(app: Express) {
    for (const provider of this.providers) {
      /**
       * 注册消息接收事件处理器
       * Register message receive event handler
       * 当收到用户消息时触发
       * Triggered when receiving user messages
       */
      provider.registerMessageReceiveEvent(app, async (userId, chatId, query) => {
        try {
          const agentService = AgentService.getUserAgentService(userId, provider);
          const contextService = ContextService.getUserContextService(userId);

          // 处理清除上下文命令
          if (query.startsWith('/clear')) {
            contextService.cleanMessage();
            await provider.sendMessage(chatId, '成功清除用户上下文 / Successfully cleared user context');
            return;
          }

          // 检查用户登录状态
          if (!contextService.isLogin) {
            await provider.sendMessage(chatId, `请点击 [登录链接](${provider.authorizeUrl}) 完成授权`);
            const success = await contextService.waitLogin();
            if (!success) {
              await provider.sendMessage(chatId, '登录超时，请重试 / Login timeout, please try again');
              return;
            }
          }
          
          if (query.startsWith('/list-tools')) {
            const context = await contextService.mustGetContext();
            let tools: Awaited<ReturnType<(typeof context.mcpClients)[number]['tools']>> = {};
            for (const mcpClient of context.mcpClients) {
              const mcpTools = await mcpClient.tools();
              tools = { ...tools, ...mcpTools };
            }
            const names = Object.keys(tools);
            await provider.sendMessage(chatId, names.length ? names.join('\n') : '无可用工具 / No tools');
            return;
          }

          // 生成AI响应
          await agentService.generateResponse(chatId, query);
        } catch (e) {
          console.error('[ChatController] 未处理的错误 / Unhandled error:', e);
          try {
            await provider.sendMessage(chatId, '发生错误，请稍后重试 / An error occurred, please try again later');
          } catch {}
        }
      });

      /**
       * 注册授权回调处理器
       * Register authorization callback handler
       * 处理用户完成OAuth授权后的回调
       * Handle callback after user completes OAuth authorization
       */
      provider.registerAuthCallback(app, async authInfo => {
        // 获取用户上下文服务并添加认证令牌
        // Get user context service and add auth token
        const contextService = ContextService.getUserContextService(authInfo.userId);
        contextService.addAuthToken(authInfo);
      });
    }
  }
}
